'''
Created on Sep 28, 2010

@author: oabalbin
'''
import os
import glob
from optparse import OptionParser
from collections import defaultdict

def read_files_folder(folderpath,ext):
    ''' '''
    # Read files in folder
    myfiles=defaultdict()
    
    for infile in glob.glob( os.path.join(folderpath, '*'+ext) ):
        filename=infile.split('/')[-1]
        myfiles[filename]=infile
        #print "current file is: " + filename
    return myfiles

def processes_trimmed_read(inputfile_name):
    inputfile = open(inputfile_name)
    outputfile = open(inputfile_name.replace('.tsv','.mdp'),'w')
    seqcount=0
    smallseq=0
    for line in inputfile:
            fields = line.strip('\n').split('\t')
            if fields[0] and (len(fields[0]) > 17):
                mycount=int(fields[1])
                outputfile.write('>tag_'+str(seqcount)+'_x'+str(mycount)+'\n')
                outputfile.write(fields[0]+'\n')
                seqcount+=mycount
            else:
                smallseq+=int(fields[1])
    
    print inputfile_name, "\t sequences with length less 14 bp \t", smallseq, "\t total other sequences \t", seqcount 
                
     
    outputfile.close()
    inputfile.close()

if __name__ == '__main__':
    
    optionparser = OptionParser("usage: %prog [options] ")
    optionparser.add_option("-d", "--folder", dest="folder",
                            help="Path to the folder that contains the .tsv files")
    (options, args) = optionparser.parse_args()
    
    folderpath = options.folder
    
    myfiles = read_files_folder(folderpath,'.tsv') 
    
    for inputfile_name in myfiles:
        processes_trimmed_read(inputfile_name)
